#!/bin/bash
#################################
# copyright by zk
# DATE:2020-09-06
#
# 自动化部署(rhel 7) 
# jdk    1.8.0_261
# redis  3.2.1
# mysql  5.7.32
# tomcat 8.5.51
# ElasticSearch-7.7.0
# Kibana-7.7.0
# FileBeat-7.7.0
# zabbix-agent
#################################
# 目录规划：
# mysql安装在/data
# redis安装在/usr/local/redis
# tomcat安装在/home下
# EFK统一rpm安装
# 脚本及安装包统一放在/opt目录下
#################################

#指定tomcat\redis\mysql 路径、端口和密码
TOMCAT_PATH=/home
TOMCAT_PORT=(7001 8001 9001)
#mysql
MYSQL_HOME=/data
MYSQL_PWD=123456
MYSQL_PORT=3306
#redis
REDIS_PATH=/usr/local
REDIS_PORT=16379
REDIS_PWD=123456
#邮箱
RELAYHOST=[xx.xx.xx.xx]:20025
MAIL_USER=xxxxx
MAIL_PWD=xxxx
#EFK路径、端口
ES_HOME=/es_data
ES_IP=xxxx81
ES_PORT=9200
KIBANA_IP=xxxx.161
KIBANA_PORT=7035
#rsync
RSYNC_USER=rsync
RSYNC_PWD=123456
RSYNC_HOME=/usr/local/rsync
RSYNC_PORT=8888
#zabbix agent
ZABBIX_SERVER=xxxx.3
ZABBIX_PORT=10050
AGENT_HOSTNAME=`hostname`


#调用函数库
[ -f /etc/init.d/functions ] && source /etc/init.d/functions
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
source /etc/profile

#Require root to run this script.
[ $(id -u) -gt 0 ] && echo "请用root用户执行此脚本！" && exit 1

#"stty erase ^H"  设置backspace为删除键
\cp /root/.bash_profile  /root/.bash_profile_$(date +%F)
erase=`grep -wx "stty erase ^H" /root/.bash_profile |wc -l`
if [ $erase -lt 1 ];then
    echo "stty erase ^H" >>/root/.bash_profile
    source /root/.bash_profile
fi


#基础变量
centosVersion=$(cat /etc/redhat-release|sed -r 's/.* ([0-9]+)\..*/\1/')
DATE=`date +"%y-%m-%d %H:%M:%S"`
IPADDR=$(ip -f inet addr | grep -v 127.0.0.1 |  grep inet |grep -vE  'inet6|127.0.0.1|virbr0'| awk '{print $NF,$2}' | tr '\n' ',' | sed 's/,$//'|awk '{print $NF}')
MAC=$(ip link | grep -v "LOOPBACK\|loopback" | awk '{print $2}' | sed 'N;s/\n//' | tr '\n' ',' | sed 's/,$//'|awk -F ',' '{print $1}')
GATEWAY=$(ip route | grep default | awk '{print $3}')
DNS=$(grep nameserver /etc/resolv.conf| grep -v "#" | awk '{print $2}' | tr '\n' ',' | sed 's/,$//')
HOSTNAME=`hostname -s`
USER=`whoami`
#disk_check  (grep -w用于字符串精确匹配)
DISK_SDA=`df -h |grep -w "/" |awk '{print $5}'`
#cpu_average_check
cpu_uptime=`cat /proc/loadavg|awk '{print $1,$2,$3}'`


#设置中文字符集
initI18n(){
  echo ""
  echo -e "\033[33m***************************************************更改中文字符集****************************************************\033[0m"
  \cp /etc/locale.conf  /etc/locale.conf.$(date +%F)
cat >>/etc/locale.conf<<EOF
LANG="zh_CN.UTF-8"
#LANG="en_US.UTF-8"
EOF
  source /etc/locale.conf
  grep LANG /etc/locale.conf
  echo -e "\033[33m***********************************************更改字符集zh_CN.UTF-8完成*********************************************\033[0m"
  echo ""
  sleep 5
}

#关闭 Selinux 和防火墙
initFirewall(){
	echo ""
  echo -e "\033[33m*************************************************禁用selinux和防火墙*************************************************\033[0m"
  \cp /etc/selinux/config /etc/selinux/config.$(date +%F)
  systemctl stop firewalld && systemctl disable firewalld
  sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
  setenforce 0
  systemctl status firewalld
  echo '#grep SELINUX=disabled /etc/selinux/config ' 
  grep SELINUX=disabled /etc/selinux/config 
  echo '#getenforce '
  getenforce 
  echo -e "\033[33m************************************************完成禁用selinux和防火墙**********************************************\033[0m"
  echo ""
  sleep 5
}


#时间同步
##$?是指上一次命令执行的成功或者失败的状态，成功为0，失败为1
syncSysTime(){
  echo ""
  echo -e "\033[33m******************************************************配置时间同步***************************************************\033[0m"
  \cp /var/spool/cron/root /var/spool/cron/root.$(date +%F) 2>/dev/null
  NTPDATE=`grep ntpdate /var/spool/cron/root 2>/dev/null |wc -l`
  if [ $NTPDATE -eq 0 ];then
  	ping -c 4 0.asia.pool.ntp.org >/dev/null 2>&1
    if [ $? -eq 0 ];then
       echo "#times sync by hwb at $(date +%F)" >>/var/spool/cron/root
       echo "*/5 * * * * /usr/sbin/ntpdate 0.asia.pool.ntp.org;/sbin/hwclock -w &>/dev/null" >> /var/spool/cron/root
       hwclock --systohc  #同步到硬件
    else
       ping -c 4 172.26.150.145 >/dev/null 2>&1
       if [ $? -eq 0 ];then
          echo "#times sync by hwb at $(date +%F)" >>/var/spool/cron/root
          echo "* 8 * * *  /usr/sbin/ntpdate 172.26.150.145;/sbin/hwclock -w" >> /var/spool/cron/root
          hwclock --systohc  #同步到硬件
       else
          echo "==============网络不通，无法配置时间同步==========="
          #exit $?和exit $1区别
          exit $?
       fi
    fi 
    
  fi 
  echo '#crontab -l'  
  crontab -l
  echo -e "\033[33m*************************************************完成时间同步配置**************************************************\033[0m"
  echo ""
  sleep 5
}


function install_yum(){
  echo ""
  echo -e "\033[33m***************************************************开始配置yum源****************************************************\033[0m"
  ping -c 4  mirrors.aliyun.com  >/dev/null
  if [ $? -eq 0 ];then
     configAliyunYum
  else
     if [ -f /root/CentOS-7-x86_64-Everything-1611.iso ];then
       	configLocalYum
     else
        action "\033[33m**********************网络不通且本地没有yum源,请手动配置yum***********************\033[0m"  /bin/true
        exit $?
     fi
  fi 
}


#Config Yum lianyou.repo and save Yum file
configLocalYum(){
  echo ""
  echo -e "\033[33m***************************************************配置本地yum*************************************************\033[0m"
  for i in /etc/yum.repos.d/*.repo;do cp $i ${i%.repo}.bak;done
  rm -rf /etc/yum.repos.d/*.repo
  mkdir -p /mnt/cdrom && mount -o loop -t iso9660 /root/CentOS-7-x86_64-Everything-1611.iso /mnt/cdrom/
  echo "================配置YUM源文件===================="
cat << EOF > /etc/yum.repos.d/localyum.repo 
[InstallMedia]
name=Centos 7.3
baseurl=file:///mnt/cdrom/
enabled=1
gpgcheck=0 
EOF
  yum clean all && yum makecache  >/dev/null 2>&1
  yum repolist
  echo -e "\033[33m***********************************************完成本地yum配置**************************************************\033[0m"
  echo ""
  sleep 5
}


#Config Yum CentOS-Bases.repo and save Yum file
configAliyunYum(){
  echo ""
  echo -e "\033[33m***************************************************更新为阿里源*****************************************************\033[0m"
  for i in /etc/yum.repos.d/*.repo;do cp $i ${i%.repo}_bak;done
  rm -rf /etc/yum.repos.d/*.repo
  wget -P /etc/yum.repos.d/ http://mirrors.aliyun.com/repo/Centos-7.repo >/dev/null 2>&1
  wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo >/dev/null 2>&1
  echo "================配置YUM源文件===================="
  sed -i 's#keepcache=0#keepcache=1#g' /etc/yum.conf     
  grep keepcache /etc/yum.conf
  yum clean all >/dev/null 2>&1
  yum makecache  >/dev/null 2>&1
  yum repolist
  echo -e "\033[33m***************************************************完成阿里源配置***************************************************\033[0m"
  echo ""
  sleep 5
}

#add user and give sudoers
addUser(){
  echo ""
  echo -e "\033[33m*****************************************************新建用户*******************************************************\033[0m"
#add user
while true
do  
    read -p "请输入新用户名:" name
    NAME=`awk -F':' '{print $1}' /etc/passwd|grep -wx $name 2>/dev/null|wc -l`
    if [ ${#name} -eq 0 ];then
       echo "用户名不能为空，请重新输入。"
       continue
    elif [ $NAME -eq 1 ];then
       echo "用户名已存在，请重新输入。"
       continue
    fi
useradd $name
break
done
#create password
while true
do
    read -p "为 $name 创建一个密码:" pass1
    if [ ${#pass1} -eq 0 ];then
       echo "密码不能为空，请重新输入。"
       continue
    fi
    read -p "请再次输入密码:" pass2
    if [ "$pass1" != "$pass2" ];then
       echo "两次密码输入不相同，请重新输入。"
       continue
    fi
echo "$pass2" |passwd --stdin $name
break
done
sleep 1

#add visudo
echo "#####add visudo#####"
\cp /etc/sudoers /etc/sudoers.$(date +%F)
SUDO=`grep -w "$name" /etc/sudoers |wc -l`
if [ $SUDO -eq 0 ];then
    echo "$name  ALL=(ALL)       NOPASSWD: ALL" >>/etc/sudoers
    echo '#tail -1 /etc/sudoers'
    grep -w "$name" /etc/sudoers
    sleep 1
fi
  #action "创建用户$name并将其加入visudo完成"  /bin/true
  echo -e "\033[33m*********************************************创建用户$name并将其加入visudo完成******************************************\033[0m"
  echo ""
  sleep 5
}



# auto install jdk 1.8
function install_jdk() 
{
  echo ""
  echo -e "\033[33m******************************************************自动部署jdk*******************************************************\033[0m"
  javac -version &>/dev/null 
	if [ $? != 0 ] ; then
		if [ -f /opt/jdk-8u221-linux-x64.tar.gz ];then
  	  echo "*****存在这个jdk压缩包，无需下载*****"
    else
      ping -c 4 vs125.hand-china.com >/dev/null 2>&1
      if [ $? -eq 0 ];then
        wget -c http://vs125.hand-china.com/111/jdk/jdk8_141.tgz  -O /opt/jdk-8u141-linux-x64.tar.gz
      else
        echo "please download jdk package manual !"
		    exit $?
      fi 
    fi
    tar -zxvf /opt/jdk-8u221-linux-x64.tar.gz -C /usr/local/ &>/dev/null
    mv /usr/local/jdk1.8.0_221 /usr/local/jdk 
    # add user env var
cat >> /etc/profile << EOF
export JAVA_HOME=/usr/local/jdk
export JRE_HOME=/usr/local/jdk/jre 
export CLASSPATH=.:/usr/local/jdk/lib:/usr/local/jdk/lib 
export PATH=/usr/local/jdk/bin:$PATH
EOF
source /etc/profile
  fi
  echo -e "\033[33m***************************************************完成jdk环境部署******************************************************\033[0m"
cat > /tmp/jdk.log  << EOF
jdk安装目录：/usr/local/jdk 
jdk版本：javac 1.8.0_221
EOF
  cat /tmp/jdk.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/jdk.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}

# auto install tomcat
function install_tomcat() 
{
	echo ""
  echo -e "\033[33m*****************************************************自动部署tomcat*****************************************************\033[0m"
	if [ -f /opt/apache-tomcat-9.0.21.tar.gz ];then
  	  echo "*****存在这个tomcat压缩包，无需下载*****"
    else
      ping -c 4 downloads.apache.org >/dev/null 2>&1
      if [ $? -eq 0 ];then
        wget -c https://downloads.apache.org/tomcat/tomcat-8/v8.5.51/bin/apache-tomcat-8.5.51.tar.gz  -O /opt/apache-tomcat-8.5.51.tar.gz
      else
        echo "please download tomcat package manual !"
		    exit $?
      fi 
  fi
  tar -zxvf /opt/apache-tomcat-9.0.21.tar.gz -C ${TOMCAT_PATH}  &>/dev/null && mv ${TOMCAT_PATH}/apache-tomcat-9.0.21 ${TOMCAT_PATH}/tomcat${TOMCAT_PORT[1]} &>/dev/null 
  # modify tomcat/conf/context.xml
  sed -i -r -e  '/<\/Context>/i \  <Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" name="jdbc/lcp_db" password="root" type="javax.sql.DataSource" url="jdbc:mysql://xx.xx.xx:3306/lcpdb" username="root"/>' ${TOMCAT_PATH}/tomcat${TOMCAT_PORT[1]}/conf/context.xml
  
  # modify http_port
  sed -i -r -e 's#.*shutdown="SHUTDOWN">.*#<Server port="'${TOMCAT_PORT[0]}'" shutdown="SHUTDOWN">#' ${TOMCAT_PATH}/tomcat${TOMCAT_PORT[1]}/conf/server.xml
  sed -i -r -e 's#.*protocol="HTTP/1.1".*#<Connector port="'${TOMCAT_PORT[1]}'" protocol="HTTP/1.1"#' ${TOMCAT_PATH}/tomcat${TOMCAT_PORT[1]}/conf/server.xml
  sed -i -r -e 's#.*protocol="org.apache.coyote.http11.Http11NioProtocol".*#<Connector port="'${TOMCAT_PORT[1]}'" protocol="org.apache.coyote.http11.Http11NioProtocol"#' ${TOMCAT_PATH}/tomcat${TOMCAT_PORT[1]}/conf/server.xml
  sed -i -r -e 's#.*protocol="AJP/1.3" redirectPort="8443" />.*#<Connector port="'${TOMCAT_PORT[2]}'" protocol="AJP/1.3" redirectPort="8443" />#' ${TOMCAT_PATH}/tomcat${TOMCAT_PORT[1]}/conf/server.xml
  # startup tomcat
  ${TOMCAT_PATH}/tomcat${TOMCAT_PORT[1]}/bin/startup.sh &>/dev/null 
  
  echo -e "\033[33m***************************************************完成tomcat环境部署***************************************************\033[0m"
cat > /tmp/tomcat.log  << EOF
tomcat安装目录：${TOMCAT_PATH}/tomcat${TOMCAT_PORT[1]}
tomcat端口：${TOMCAT_PORT[1]}
tomcat版本：tomcat-9.0.21
EOF
  cat /tmp/tomcat.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/tomcat.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}


# auto install redis-3.2
function install_redis() 
{
	echo ""
  echo -e "\033[33m****************************************************自动部署redis*******************************************************\033[0m"
  #创建用户
  groupadd -r redis && useradd -r -g redis redis -d /home/redis -m
  
  #下载包
	if [ -f /opt/redis-3.2.1.tar.gz ];then
		echo "*****存在redis压缩包，无需下载*****"
    else
      ping -c 4 download.redis.io >/dev/null 2>&1
      if [ $? -eq 0 ];then
        wget -c http://download.redis.io/releases/redis-3.2.1.tar.gz  -O /opt/redis-3.2.1.tar.gz
      else
        echo "please download redis package manual !"
		    exit $?
      fi 
  fi
  
  #配yum安装gcc
  rpm -qa|grep gcc-c++
  if [ $? -eq 1 ];then
    install_yum
    yum install -y gcc*  &>/dev/null
    sleep 3
    echo "安装gcc成功!"
  fi 
  
  #编译安装
  tar -xvf /opt/redis-3.2.1.tar.gz -C  ${REDIS_PATH} &>/dev/null
  cd  ${REDIS_PATH}/redis-3.2.1 &>/dev/null && make &>/dev/null && make install  &>/dev/null
  sleep 3
  # check install result
  ${REDIS_PATH}/redis-3.2.1/src/redis-server -v 
  if [ $? -eq 0 ] ;then
    echo "*****redis install successfully!*****"
  else
	  echo "*****redis install error!*****"
	  exit $?
  fi
  
  #安全配置
  sed -i "s/port 6379/port ${REDIS_PORT}/g"   ${REDIS_PATH}/redis-3.2.1/redis.conf   #sed替换变量需要把单引号改成双引号
  sed -i 's/daemonize no/daemonize yes/g'   ${REDIS_PATH}/redis-3.2.1/redis.conf 
  sed -i 's/protected-mode yes/protected-mode no/g'   ${REDIS_PATH}/redis-3.2.1/redis.conf 
  sed -i 's/bind 127.0.0.1/bind 0.0.0.0/g'   ${REDIS_PATH}/redis-3.2.1/redis.conf   
cat >>  ${REDIS_PATH}/redis-3.2.1/redis.conf << EOF
requirepass ${REDIS_PWD}
rename-command FLUSHALL ""
rename-command CONFIG ""
rename-command EVAL ""
EOF
  
  #启动redis
   ${REDIS_PATH}/redis-3.2.1/src/redis-server  ${REDIS_PATH}/redis-3.2.1/redis.conf
  ps -ef |grep redis|grep -v grep
  if [ $? -eq 0 ] ;then
     echo "*****redis start success!*****"
  else
	  exit $?
	  echo "*****redis start error!*****"
  fi
  
  echo -e "\033[33m***************************************************完成redis环境部署***************************************************\033[0m"
cat > /tmp/redis.log  << EOF
redis安装目录：/usr/local/redis-3.2.1
redis版本：redis-3.2.1
redis端口：${REDIS_PORT}
redis密码：${REDIS_PWD}
EOF
  cat /tmp/redis.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/redis.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}

# auto install el7 mysql 5.7
function install_mysql5.7_el7() 
{
	echo ""
  echo -e "\033[33m******************************************************自动部署mysql5.7*****************************************************\033[0m" 
  #建用户及目录
  groupadd -r mysql && useradd -r -g mysql mysql -d /home/mysql -m
  mkdir -p $MYSQL_HOME/datafile &&  mkdir -p $MYSQL_HOME/log
  chown -R mysql:mysql $MYSQL_HOME && chmod -R 755 $MYSQL_HOME

  #关闭selinux
  setenforce 0
  sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
   
  #下载包
  if [ -f /opt/mysql-community-server-5.7.32-1.el7.x86_64.rpm ] && [ -f /opt/mysql-community-client-5.7.32-1.el7.x86_64.rpm ] && [ -f /opt/mysql-community-libs-5.7.32-1.el7.x86_64.rpm ] && [ -f /opt/mysql-community-common-5.7.32-1.el7.x86_64.rpm ];then
	  echo "*****存在mysql安装包，无需下载*****"
  else
      ping -c 4 cdn.mysql.com >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-community-server-5.7.32-1.el7.x86_64.rpm  -P /opt
        wget https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-community-client-5.7.32-1.el7.x86_64.rpm  -P /opt
        wget https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-community-libs-5.7.32-1.el7.x86_64.rpm    -P /opt
        wget https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-community-common-5.7.32-1.el7.x86_64.rpm  -P /opt
        wget https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-community-libs-compat-5.7.32-1.el7.x86_64.rpm -P /opt
      else
        echo "please download mysql package manual !"
		exit $?
      fi 
  fi
  
  #安装mysql
  ps -ef|grep mysql |grep -v grep
  if [ $? -eq 0 ] ;then
     echo "*****已存在mysql进程*****"
     exit $?
  else
	   # 卸载 mysql
     rpm -qa|grep mysql|xargs -i rpm -e --nodeps {} 
     # uninstall mariadb
     rpm -qa|grep "mariadb"|xargs -i rpm -e --nodeps {} 
     # 安装mysql
	 rpm -ivh /opt/mysql-community-common-5.7.32-1.el7.x86_64.rpm
	 rpm -ivh /opt/mysql-community-libs-5.7.32-1.el7.x86_64.rpm
	 rpm -ivh /opt/mysql-community-client-5.7.32-1.el7.x86_64.rpm
     rpm -ivh /opt/mysql-community-server-5.7.32-1.el7.x86_64.rpm
     rpm -ivh /opt/mysql-community-libs-compat-5.7.32-1.el7.x86_64.rpm
     rpm -ivh /opt/mysql-community-devel-5.7.32-1.el7.x86_64.rpm
  fi
  
  #配置my.cnf
  cp /etc/my.cnf /etc/my.cnf_${DATE}bak &>/dev/null 
cat << EOF > /etc/my.cnf 
[mysqld]
#解决时区问题
default-time-zone = '+8:00'
#解决mysql日志时间与系统时间不一致问题
log_timestamps=SYSTEM
port=${MYSQL_PORT}
datadir=${MYSQL_HOME}/datafile
log-error=${MYSQL_HOME}/log/mysqld.log
symbolic-links=0
bind-address=0.0.0.0
lower_case_table_names=1
character_set_server=utf8
max_allowed_packet=500M
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
#InnoDB用于缓存数据、索引、锁、插入缓冲、数据字典等
innodb_buffer_pool_size=4G
#InnoDB的log buffer
innodb_log_buffer_size = 64M
#InnoDB redo log大小
innodb_log_file_size = 256M
#InnoDB redo log文件组
innodb_log_files_in_group = 2
innodb_flush_log_at_trx_commit = 2
lower_case_table_names=1
#连接数
max_connections=600
max_connect_errors=1000
max_user_connections=400
#设置临时表最大值
max_heap_table_size = 100M
tmp_table_size = 100M
#每个连接都会分配的一些排序、连接等缓冲
sort_buffer_size = 2M
join_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 2M
#关闭query cache
query_cache_size = 0
#如果是以InnoDB引擎为主的DB，专用于MyISAM引擎的 key_buffer_size 可以设置较小，8MB 已足够,如果是以MyISAM引擎为主，可设置较大，但不能超过4G
key_buffer_size = 8M
#设置慢查询阀值，单位为秒
long_query_time = 60
slow_query_log=1         
log_output=table,File    #日志输出会写表，也会写日志文件，为了便于程序去统计，所以最好写表
slow_query_log_file=${MYSQL_HOME}/log/slow.log
#快速预热缓冲池
innodb_buffer_pool_dump_at_shutdown=1
innodb_buffer_pool_load_at_startup=1
#打印deadlock日志
innodb_print_all_deadlocks=1
#二进制配置
server-id = 1
log-bin = ${MYSQL_HOME}/log/mysql-bin.log
log-bin-index =${MYSQL_HOME}/log/binlog.index
log_bin_trust_function_creators=1
expire_logs_days=15
#timeout
wait_timeout = 3600
interactive_timeout = 3600
net_read_timeout = 3600
net_write_timeout = 3600
#schedule
event_scheduler = on
#兼容5.6
show_compatibility_56=on
#处理TIMESTAMP with implicit DEFAULT value is deprecated
explicit_defaults_for_timestamp=true
EOF

#启动数据库
systemctl start mysqld.service
MYSQL_TEMP_PWD=$(grep "temporary password" ${MYSQL_HOME}/log/mysqld.log|cut -d "@" -f 2|awk '{print $2}')
mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p${MYSQL_TEMP_PWD} -e "set global validate_password_policy=0" --connect-expired-password
mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p${MYSQL_TEMP_PWD} -e "set global validate_password_length=1" --connect-expired-password
mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p${MYSQL_TEMP_PWD} -e "SET PASSWORD = PASSWORD('${MYSQL_PWD}')"  --connect-expired-password
mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p${MYSQL_PWD} -e "grant all privileges on *.* to root@'%' identified by '${MYSQL_PWD}'" --connect-expired-password
  
echo -e "\033[33m**************************************************完成mysql5.7数据库部署***************************************************\033[0m"
cat > /tmp/mysql.log  << EOF
mysql安装目录：${MYSQL_HOME}
mysql版本：Mysql-5.7.32
mysql端口：${MYSQL_PORT}
mysql密码：${MYSQL_PWD}
EOF
  cat /tmp/mysql.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/mysql.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}

# # install mysql
# function install_mysql()
# {
# if [ ${centosVersion} == 6 ];then
# 	 install_mysql_el6
# elif [ ${centosVersion} == 7 ];then
#    install_mysql_el7
# else
#    echo "your select OS version is error,please retry !"
# 	 exit 1
# fi
# }


function install_mysql8_el7() 
{
	echo ""
  echo -e "\033[33m***************************************************自动部署mysql8.0**************************************************\033[0m" 
  #建用户及目录
  groupadd -r mysql && useradd -r -g mysql mysql -d /home/mysql -m
  mkdir -p $MYSQL_HOME/datafile &&  mkdir -p $MYSQL_HOME/log
  chown -R mysql:mysql $MYSQL_HOME && chmod -R 755 $MYSQL_HOME

  #关闭selinux
  setenforce 0
  sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
  
  #下载包
  if [ -f /opt/mysql-8.0.19-1.el7.x86_64.rpm-bundle.tar ];then
      echo "*****存在mysql8安装包，无需下载*****"
  else
      ping -c 4 cdn.mysql.com >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget https://cdn.mysql.com//Downloads/MySQL-8.0/mysql-8.0.19-1.el7.x86_64.rpm-bundle.tar  -P /opt
      else
        echo "please download mysql8 package manual !"
		exit $?
      fi 
  fi
  
  #配yum安装mysql依赖包
  rpm -qa|grep openssl-devel
  if [ $? -eq 1 ];then
    install_yum
    yum install -y gcc gcc-c++ openssl openssl-devel libaio libaio-devel  ncurses  ncurses-devel &>/dev/null 
    action "***************安装mysql依赖包完成***************" /bin/true  
    else
    	action "****************已安装mysql依赖包****************" /bin/true 
  fi

  #安装mysql8.0
  ps -ef|grep mysql |grep -v grep
  if [ $? -eq 0 ] ;then
     echo "*****************已存在mysql进程*****************"
     exit $?
  else
	 # 卸载 mysql
     rpm -qa|grep mysql|xargs -i rpm -e --nodeps {} 
     # uninstall mariadb-libs
     rpm -qa|grep mariadb|xargs -i rpm -e --nodeps {} 
     # 安装mysql
     action "***************开始安装mysql数据库***************" /bin/true
     tar -xvf /opt/mysql-8.0.19-1.el7.x86_64.rpm-bundle.tar -C  /opt/  &>/dev/null
     rpm -ivh /opt/mysql-community-common-8.0.19-1.el7.x86_64.rpm
	 rpm -ivh /opt/mysql-community-embedded-compat-8.0.19-1.el7.x86_64.rpm
	 rpm -ivh /opt/mysql-community-libs-8.0.19-1.el7.x86_64.rpm
     rpm -ivh /opt/mysql-community-libs-compat-8.0.19-1.el7.x86_64.rpm
     rpm -ivh /opt/mysql-community-devel-8.0.19-1.el7.x86_64.rpm
     rpm -ivh /opt/mysql-community-client-8.0.19-1.el7.x86_64.rpm
     rpm -ivh /opt/mysql-community-server-8.0.19-1.el7.x86_64.rpm
     #mysql-community-test-8.0.19-1.el7.x86_64.rpm
  fi
  
  #配置my.cnf
  cp /etc/my.cnf /etc/my.cnf_${DATE}bak &>/dev/null 
cat << EOF > /etc/my.cnf 
[mysqld]
#解决时区问题
default-time-zone = '+8:00'
#解决mysql日志时间与系统时间不一致问题
log_timestamps=SYSTEM
port=${MYSQL_PORT}
datadir=${MYSQL_HOME}/datafile
log-error=${MYSQL_HOME}/log/mysqld.log
#mysql8默认禁用Symbolic links，无需再去标记禁用
#symbolic-links=0
bind-address=0.0.0.0
lower_case_table_names=1
character_set_server=utf8mb4
max_allowed_packet=500M
#SQL Mode的NO_AUTO_CREATE_USER取消
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
#InnoDB用于缓存数据、索引、锁、插入缓冲、数据字典等
innodb_buffer_pool_size=4G
#InnoDB的log buffer
innodb_log_buffer_size = 64M
#InnoDB redo log大小
innodb_log_file_size = 256M
#InnoDB redo log文件组
innodb_log_files_in_group = 2
innodb_flush_log_at_trx_commit = 2
#连接数
max_connections=600
max_connect_errors=1000
max_user_connections=400
#设置临时表最大值
max_heap_table_size = 100M
tmp_table_size = 100M
#每个连接都会分配的一些排序、连接等缓冲
sort_buffer_size = 2M
join_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 2M
#mysql8自动关闭query cache
#query_cache_size = 0
#如果是以InnoDB引擎为主的DB，专用于MyISAM引擎的 key_buffer_size 可以设置较小，8MB 已足够,如果是以MyISAM引擎为主，可设置较大，但不能超过4G
key_buffer_size = 8M
#设置慢查询阀值，单位为秒
long_query_time = 60
slow_query_log=1         
log_output=table,File    #日志输出会写表，也会写日志文件，为了便于程序去统计，所以最好写表
slow_query_log_file=${MYSQL_HOME}/log/slow.log
#快速预热缓冲池
innodb_buffer_pool_dump_at_shutdown=1
innodb_buffer_pool_load_at_startup=1
#打印deadlock日志
innodb_print_all_deadlocks=1
#二进制配置
server-id = 1
log-bin = ${MYSQL_HOME}/log/mysql-bin.log
log-bin-index =${MYSQL_HOME}/log/binlog.index
log_bin_trust_function_creators=1
binlog_format = row
gtid_mode = ON
enforce_gtid_consistency = ON
#expire-logs-days参数取消，修改成binlog_expire_logs_seconds,单位为秒，以下代表15天
binlog_expire_logs_seconds=1296000
#schedule
event_scheduler = on
#unknown variable 'show_compatibility_56=on'
#show_compatibility_56=on
#处理TIMESTAMP with implicit DEFAULT value is deprecated
explicit_defaults_for_timestamp=true
#MySQL 8.0改了默认加密方式为“caching_sha2_password”，这里改回来
default_authentication_plugin=mysql_native_password
#禁用SSL提高性能
skip_ssl
#timeout
wait_timeout = 3600
interactive_timeout = 3600
net_read_timeout = 3600
net_write_timeout = 3600
EOF

  #启动数据库
  systemctl start mysqld.service
  sleep 3
  MYSQL_TEMP_PWD=$(grep "temporary password" ${MYSQL_HOME}/log/mysqld.log|cut -d "@" -f 2|awk '{print $2}')
  #mysql 8密码策略validate_password_policy 变为validate_password.policy
  #MYSQL 8.0内新增加mysql_native_password函数，通过更改这个函数密码来进行远程连接
  mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p"${MYSQL_TEMP_PWD}" -e "set global validate_password.policy=0" --connect-expired-password
  mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p"${MYSQL_TEMP_PWD}" -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '${MYSQL_PWD}'"  --connect-expired-password 
  mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p"${MYSQL_PWD}" -e "CREATE USER 'root'@'%' IDENTIFIED BY '${MYSQL_PWD}'"  --connect-expired-password
  mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p"${MYSQL_PWD}" -e "grant all privileges on *.* to root@'%'"  --connect-expired-password   
  #授权root远程登录需输入以下命令：
  #create user root@'%' identified by 'fswl@1234';
  #grant all privileges on *.* to root@'%';
  echo -e "\033[33m************************************************完成mysql8.0数据库部署*************************************************\033[0m"
cat > /tmp/mysql8.log  << EOF
mysql安装目录：${MYSQL_HOME}
mysql版本：Mysql-8.0
mysql端口：${MYSQL_PORT}
mysql密码：${MYSQL_PWD}
EOF
  cat /tmp/mysql8.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/mysql8.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}



function install_percona_server8_el7() 
{
	echo ""
  echo -e "\033[33m**********************************************自动部署Percona Server for MySQL 8.0*********************************************\033[0m" 
  #建用户及目录
  groupadd -r mysql && useradd -r -g mysql mysql -d /home/mysql -m
  mkdir -p $MYSQL_HOME/datafile &&  mkdir -p $MYSQL_HOME/log
  chown -R mysql:mysql $MYSQL_HOME && chmod -R 755 $MYSQL_HOME

  #关闭selinux
  setenforce 0
  sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
  
  #下载包
  if [ -f /opt/Percona-Server-8.0.19-10-rf446c04-el7-x86_64-bundle.tar ];then
      echo "*****存在Percona Server for MySQL 8.0安装包，无需下载*****"
  else
      ping -c 4 www.percona.com >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget https://www.percona.com/downloads/Percona-Server-LATEST/Percona-Server-8.0.19-10/binary/redhat/7/x86_64/Percona-Server-8.0.19-10-rf446c04-el7-x86_64-bundle.tar  -P /opt
      else
        echo "please download Percona Server for MySQL 8.0 package manual !"
		    exit $?
      fi 
  fi
  
  #编译安装jemalloc
  #wget https://github.com/jemalloc/jemalloc/releases/download/4.2.1/jemalloc-4.2.1.tar.bz2
  # ./configure && make && make install  && echo '/usr/local/lib' > /etc/ld.so.conf.d/local.conf && ldconfig
  
  
  #配yum安装Percona Server for MySQL 8.0依赖包
  rpm -qa|grep jemalloc
  if [ $? -eq 1 ];then
    install_yum
    yum install -y gcc gcc-c++ openssl openssl-devel libaio libaio-devel  ncurses  ncurses-devel net-tools perl perl-Data-Dumper  perl-JSON &>/dev/null 
    yum install -y jemalloc &>/dev/null  
    action "************安装Percona Server for MySQL 8.0依赖包完成************" /bin/true  
    else
    	action "************已安装Percona Server for MySQL 8.0依赖包************" /bin/true 
  fi

  #安装Percona Server for MySQL 8.0
  ps -ef|grep mysql |grep -v grep
  if [ $? -eq 0 ] ;then
     echo "*****************已存在mysql进程*****************"
     exit $?
  else
	   # 卸载 mysql
     rpm -qa|grep mysql|xargs -i rpm -e --nodeps {} 
     # uninstall mariadb-libs
     rpm -qa|grep mariadb|xargs -i rpm -e --nodeps {} 
     # 安装mysql
     action "*************开始安装Percona Server for MySQL 8.0数据库**************" /bin/true
     tar -xvf /opt/Percona-Server-8.0.19-10-rf446c04-el7-x86_64-bundle.tar -C  /opt/  &>/dev/null
     rpm -ivh /opt/percona-*.rpm
  fi
  
  #关闭THP
  echo never > /sys/kernel/mm/redhat_transparent_hugepage/enabled
  echo never > /sys/kernel/mm/redhat_transparent_hugepage/defrag
  
  #配置my.cnf
  cp /etc/my.cnf /etc/my.cnf_${DATE}bak &>/dev/null 
cat << EOF > /etc/my.cnf 
[mysqld]
port=${MYSQL_PORT}
datadir=${MYSQL_HOME}/datafile
log-error=${MYSQL_HOME}/log/mysqld.log
#mysql8默认禁用Symbolic links，无需再去标记禁用
#symbolic-links=0
bind-address=0.0.0.0
lower_case_table_names=1
character_set_server=utf8mb4
max_allowed_packet=500M
#SQL Mode的NO_AUTO_CREATE_USER取消
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
#InnoDB用于缓存数据、索引、锁、插入缓冲、数据字典等
innodb_buffer_pool_size=4G
#InnoDB的log buffer
innodb_log_buffer_size = 64M
#InnoDB redo log大小
innodb_log_file_size = 256M
#InnoDB redo log文件组
innodb_log_files_in_group = 2
innodb_flush_log_at_trx_commit = 2
#连接数
max_connections=600
max_connect_errors=1000
max_user_connections=400
#设置临时表最大值
max_heap_table_size = 100M
tmp_table_size = 100M
#每个连接都会分配的一些排序、连接等缓冲
sort_buffer_size = 2M
join_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 2M
#mysql8自动关闭query cache
#query_cache_size = 0
#如果是以InnoDB引擎为主的DB，专用于MyISAM引擎的 key_buffer_size 可以设置较小，8MB 已足够,如果是以MyISAM引擎为主，可设置较大，但不能超过4G
key_buffer_size = 8M
#设置慢查询阀值，单位为秒
long_query_time = 60
slow_query_log=1         
log_output=table,File    #日志输出会写表，也会写日志文件，为了便于程序去统计，所以最好写表
slow_query_log_file=${MYSQL_HOME}/log/slow.log
#快速预热缓冲池
innodb_buffer_pool_dump_at_shutdown=1
innodb_buffer_pool_load_at_startup=1
#打印deadlock日志
innodb_print_all_deadlocks=1
#二进制配置
server-id = 1
log-bin = ${MYSQL_HOME}/log/mysql-bin.log
log-bin-index =${MYSQL_HOME}/log/binlog.index
log_bin_trust_function_creators=1
#expire-logs-days参数取消，修改成binlog_expire_logs_seconds,单位为秒，以下代表15天
binlog_expire_logs_seconds=1296000
#schedule
event_scheduler = on
#unknown variable 'show_compatibility_56=on'
#show_compatibility_56=on
#处理TIMESTAMP with implicit DEFAULT value is deprecated
explicit_defaults_for_timestamp=true
#默认加密方式
default_authentication_plugin=mysql_native_password
EOF

  #启动数据库
  systemctl start mysqld.service
  sleep 3
  MYSQL_TEMP_PWD=$(grep "temporary password" ${MYSQL_HOME}/log/mysqld.log|cut -d "@" -f 2|awk '{print $2}')
  mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p"${MYSQL_TEMP_PWD}" -e "set global validate_password.policy=0" --connect-expired-password
  mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p"${MYSQL_TEMP_PWD}" -e "ALTER USER 'root'@'localhost' IDENTIFIED  BY '${MYSQL_PWD}';flush privileges"  --connect-expired-password  
  mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p"${MYSQL_PWD}" -e "CREATE USER 'root'@'%' IDENTIFIED BY '${MYSQL_PWD}'"  --connect-expired-password
  mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p"${MYSQL_PWD}" -e "grant all privileges on *.* to root@'%'"  --connect-expired-password   
  #授权root远程登录需输入以下命令：
  #create user root@'%' identified by 'fswl@1234';
  #grant all privileges on *.* to root@'%';
  echo -e "\033[33m*******************************************完成Percona Server for MySQL 8.0数据库部署********************************************\033[0m"
cat > /tmp/percona_mysql8.log  << EOF
mysql安装目录：${MYSQL_HOME}
mysql版本：Percona Server for MySQL 8.0
mysql端口：${MYSQL_PORT}
mysql密码：${MYSQL_PWD}
mysql状态：`systemctl status mysqld`
EOF
  cat /tmp/percona_mysql8.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/percona_mysql8.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}


function install_mariadb10_el7() 
{
	echo ""
  echo -e "\033[33m***********************************************自动部署mariadb-10.4.13**********************************************\033[0m" 
  #建用户及目录
  groupadd -r mysql && useradd -r -g mysql mysql -d /home/mysql -m
  mkdir -p $MYSQL_HOME/datafile &&  mkdir -p $MYSQL_HOME/log
  chown -R mysql:mysql $MYSQL_HOME && chmod -R 755 $MYSQL_HOME

  #关闭selinux
  setenforce 0
  sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
  
  #下载libzstd-1.3.4
  if [ -f /opt/libzstd-1.3.4-1.el7.x86_64.rpm ];then
      echo "*****存在libzstd-1.3.4安装包，无需下载*****"
  else
      ping -c 4 mirror.kku.ac.th >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget http://mirror.kku.ac.th/mariadb//mariadb-10.4.13/yum/centos7-amd64/rpms/libzstd-1.3.4-1.el7.x86_64.rpm  -P /opt
      else
        echo "please download libzstd-1.3.4 package manual !"
		    exit $?
      fi 
  fi
  
  #下载jemalloc
  if [ -f /opt/jemalloc-3.6.0-1.el7.x86_64.rpm ] && [ -f /opt/jemalloc-devel-3.6.0-1.el7.x86_64.rpm ] ;then
      echo "*****存在jemalloc安装包，无需下载*****"
  else
      ping -c 4 mirror.kku.ac.th >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget http://mirror.kku.ac.th/mariadb//mariadb-10.4.13/yum/centos7-amd64/rpms/jemalloc-3.6.0-1.el7.x86_64.rpm  -P /opt
      	wget http://mirror.kku.ac.th/mariadb//mariadb-10.4.13/yum/centos7-amd64/rpms/jemalloc-devel-3.6.0-1.el7.x86_64.rpm  -P /opt
      else
        echo "please download jemalloc package manual!"
		    exit $?
      fi 
  fi
  
  #下载libboost_program_options.so.1.53和 galera-4-26
  if [ -f /opt/boost-program-options-1.53.0-28.el7.x86_64.rpm ] && [ -f /opt/galera-4-26.4.4-1.rhel7.el7.centos.x86_64.rpm ] ;then
      echo "*****存在galera安装包，无需下载*****"
  else
      ping -c 4 mirror.kku.ac.th >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget  -P ftp://ftp.pbone.net/mirror/ftp.centos.org/7.8.2003/os/x86_64/Packages/boost-program-options-1.53.0-28.el7.x86_64.rpm /opt
      	wget  -P http://mirror.kku.ac.th/mariadb//mariadb-10.4.13/yum/centos7-amd64/rpms/galera-4-26.4.4-1.rhel7.el7.centos.x86_64.rpm /opt
      else
        echo "please download galera-4-26 package manual !"
		    exit $?
      fi 
  fi
  
  #http://mirror.centos.org/centos/7/os/x86_64/Packages/perl-DBI-1.627-4.el7.x86_64.rpm
  #下载perl-DBI相关包
#  perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64.rpm
#  perl-Compress-Raw-Zlib-2.061-4.el7.x86_64.rpm
#  perl-Data-Dumper-2.145-3.el7.x86_64.rpm
#  perl-DBI-1.627-4.el7.x86_64.rpm
#  perl-IO-Compress-2.061-2.el7.noarch.rpm
#  perl-Net-Daemon-0.48-5.el7.noarch.rpm
#  perl-PlRPC-0.2020-14.el7.noarch.rpm
  if [ -f /opt/perl-DBI-1.627-4.el7.x86_64.rpm ] ;then
      echo "*****存在perl-DBI安装包，无需下载*****"
  else
      ping -c 4 mirror.centos.org >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget  -P http://mirror.centos.org/centos/7/os/x86_64/Packages/perl-DBI-1.627-4.el7.x86_64.rpm /opt
      else
        echo "please download perl-DBI package manual !"
		    exit $?
      fi 
  fi
  
  #从MariaDB 10.1.20 版本开始，Galera Cluster就已经包含在MariaDB包里面了，不需要单独部署MariaDB-Galera-server 和galera包。  
  #下载mariadb包
  if [ -f /opt/MariaDB-client-10.4.13-1.el7.centos.x86_64.rpm ] && [ -f /opt/MariaDB-common-10.4.13-1.el7.centos.x86_64.rpm ]  && [ -f /opt/MariaDB-compat-10.4.13-1.el7.centos.x86_64.rpm ] && [ -f /opt/MariaDB-devel-10.4.13-1.el7.centos.x86_64.rpm ] && [  -f /opt/MariaDB-server-10.4.13-1.el7.centos.x86_64.rpm ] ;then
      echo "*****存在mariadb 10.4.13安装包，无需下载*****"
  else
      ping -c 4 www.percona.com >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget  -P http://mirror.kku.ac.th/mariadb//mariadb-10.4.13/yum/centos7-amd64/rpms/MariaDB-client-10.4.13-1.el7.centos.x86_64.rpm /opt
      	wget  -P http://mirror.kku.ac.th/mariadb//mariadb-10.4.13/yum/centos7-amd64/rpms/MariaDB-common-10.4.13-1.el7.centos.x86_64.rpm /opt
      	wget  -P http://mirror.kku.ac.th/mariadb//mariadb-10.4.13/yum/centos7-amd64/rpms/MariaDB-compat-10.4.13-1.el7.centos.x86_64.rpm /opt
      	wget  -P http://mirror.kku.ac.th/mariadb//mariadb-10.4.13/yum/centos7-amd64/rpms/MariaDB-server-10.4.13-1.el7.centos.x86_64.rpm /opt
      	wget  -P http://mirror.kku.ac.th/mariadb//mariadb-10.4.13/yum/centos7-amd64/rpms/MariaDB-devel-10.4.13-1.el7.centos.x86_64.rpm /opt
      else
        echo "please download mariadb 10.4.13 package manual !"
		    exit $?
      fi 
  fi
  
  
  #配yum安装mariadb 10.4.13依赖包
  rpm -qa|grep perl-JSON
  if [ $? -eq 1 ];then
    install_yum
    yum install -y gcc gcc-c++ openssl openssl-devel libaio libaio-devel  ncurses ncurses-devel net-tools perl  perl-JSON &>/dev/null 
    action "************安装mariadb 10.4.13依赖包完成************" /bin/true  
    else
    	action "************已安装mariadb 10.4.13依赖包************" /bin/true 
  fi

  #安装Percona Server for MySQL 8.0
  ps -ef|grep mysql |grep -v grep
  if [ $? -eq 0 ] ;then
     echo "*****************已存在mysql进程*****************"
     exit $?
  else
	   # 卸载 mysql
     rpm -qa|grep mysql|xargs -i rpm -e --nodeps {} 
     # 卸载 mariadb-libs
     rpm -qa|grep mariadb|xargs -i rpm -e --nodeps {} 
     rpm -qa|grep mariadb-libs|xargs -i rpm -e --nodeps {} 
     # 安装mysql
     action "*************开始安装mariadb 10.4.13数据库**************" /bin/true
     rpm -ivh /opt/libzstd-1.3.4-1.el7.x86_64.rpm 
     rpm -ivh /opt/jemalloc-3.6.0-1.el7.x86_64.rpm
     rpm -ivh /opt/jemalloc-devel-3.6.0-1.el7.x86_64.rpm
     #安装 boost-devel 依赖环境
     rpm -ivh /opt/boost-program-options-1.53.0-28.el7.x86_64.rpm
     #安装 galera 环境
     rpm -ivh /opt/galera-4-26.4.4-1.rhel7.el7.centos.x86_64.rpm
     rpm -ivh /opt/perl*.rpm
     rpm -ivh /opt/MariaDB-*.rpm
  fi
  
  #初始化数据并启动数据库
  systemctl start mariadb.service  
  sleep 3
 
  #转移数据文件目录
  systemctl stop mariadb
  cp -raf /var/lib/mysql/*  ${MYSQL_HOME}/datafile
  
  #配置my.cnf
  cp /etc/my.cnf /etc/my.cnf_${DATE}bak &>/dev/null 
cat << EOF > /etc/my.cnf 
[mysqld]
port=${MYSQL_PORT}
datadir=${MYSQL_HOME}/datafile
log_error = ${MYSQL_HOME}/log/mariadb.log
#mysql8默认禁用Symbolic links，无需再去标记禁用
#symbolic-links=0
bind-address=0.0.0.0
lower_case_table_names=1
character_set_server=utf8mb4
max_allowed_packet=500M
#SQL Mode的NO_AUTO_CREATE_USER取消
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
#InnoDB用于缓存数据、索引、锁、插入缓冲、数据字典等
innodb_buffer_pool_size=4G
#InnoDB的log buffer
innodb_log_buffer_size = 64M
#InnoDB redo log大小
innodb_log_file_size = 256M
#InnoDB redo log文件组
innodb_log_files_in_group = 2
innodb_flush_log_at_trx_commit = 2
#连接数
max_connections=600
max_connect_errors=1000
max_user_connections=400
#设置临时表最大值
max_heap_table_size = 100M
tmp_table_size = 100M
#每个连接都会分配的一些排序、连接等缓冲
sort_buffer_size = 2M
join_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 2M
bulk_insert_buffer_size = 32M                   #批量插入数据缓存大小
#关闭query cache
#query_cache_size = 0
#如果是以InnoDB引擎为主的DB，专用于MyISAM引擎的 key_buffer_size 可以设置较小，8MB 已足够,如果是以MyISAM引擎为主，可设置较大，但不能超过4G
key_buffer_size = 8M
#设置慢查询阀值，单位为秒
long_query_time = 60
slow_query_log=1         
log_output=table,File    #日志输出会写表，也会写日志文件，为了便于程序去统计，所以最好写表
slow_query_log_file=${MYSQL_HOME}/log/slow.log
#快速预热缓冲池
innodb_buffer_pool_dump_at_shutdown=1
innodb_buffer_pool_load_at_startup=1
#打印deadlock日志
innodb_print_all_deadlocks=1
#二进制配置
server-id = 1
log-bin = ${MYSQL_HOME}/log/mysql-bin.log
log-bin-index =${MYSQL_HOME}/log/binlog.index
log_bin_trust_function_creators=1
expire-logs-days=7
#schedule
event_scheduler = on
#unknown variable 'show_compatibility_56=on'
#show_compatibility_56=on
#处理TIMESTAMP with implicit DEFAULT value is deprecated
explicit_defaults_for_timestamp=true
open_files_limit = 65535 
EOF
  systemctl start mariadb
  #安全设置mysql_secure_installation
  #MYSQL_TEMP_PWD=$(grep "temporary password" ${MYSQL_HOME}/log/mysqld.log|cut -d "@" -f 2|awk '{print $2}')
  #mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p"${MYSQL_TEMP_PWD}" -e "set global validate_password.policy=0" --connect-expired-password
  #mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p"${MYSQL_TEMP_PWD}" -e "ALTER USER 'root'@'localhost' IDENTIFIED  BY '${MYSQL_PWD}';flush privileges"  --connect-expired-password  
  #mysql -hlocalhost  -P${MYSQL_PORT}  -uroot -p${MYSQL_PWD} -e "grant all privileges on *.* to root@'%' identified by '${MYSQL_PWD}'" --connect-expired-password
  mysql -uroot -p"${MYSQL_PWD}" -e "CREATE USER 'root'@'%' IDENTIFIED BY '${MYSQL_PWD}'"  --connect-expired-password
  mysql -uroot -p"${MYSQL_PWD}" -e "grant all privileges on *.* to root@'%'"  --connect-expired-password   
  #授权root远程登录需输入以下命令：
  #create user root@'%' identified by 'fswl@1234';
  #grant all privileges on *.* to root@'%';
  echo -e "\033[33m*******************************************完成mariadb-10.4.13数据库部署********************************************\033[0m"
cat > /tmp/mariadb-10.4.13.log << EOF
mariadb安装目录：${MYSQL_HOME}
mariadb版本：mariadb-10.4.13
mariadb端口：${MYSQL_PORT}
mariadb密码：${MYSQL_PWD}
mariadb状态：`systemctl status mariadb`
EOF
  cat /tmp/mariadb-10.4.13.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/mariadb-10.4.13.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}




function install_xtrabackup2.4_el7() 
{
	echo ""
  echo -e "\033[33m**********************************************自动部署Percona xtrabackup 2.4*********************************************\033[0m" 
  
  #下载包
  if [ -f /opt/percona-xtrabackup-24-2.4.20-1.el7.x86_64.rpm ] && [ -f /opt/libev-4.15-3.el7.x86_64.rpm ] ;then
      echo "*****存在Percona xtrabackup 2.4安装包，无需下载*****"
  else
      ping -c 4 www.percona.com >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget http://rpmfind.net/linux/epel/7/x86_64/Packages/l/libev-4.15-3.el7.x86_64.rpm  -P /opt
      	#wget http://mirror.centos.org/centos/7/os/x86_64/Packages/perl-Digest-MD5-2.52-3.el7.x86_64.rpm -P /opt
      	wget https://www.percona.com/downloads/Percona-XtraBackup-2.4/Percona-XtraBackup-2.4.20/binary/redhat/7/x86_64/percona-xtrabackup-24-2.4.20-1.el7.x86_64.rpm  -P /opt
      else
        echo "please download Percona xtrabackup 2.4 package manual !"
		    exit $?
      fi 
  fi  
    
  #配yum安装perl-DBD-MySQL和perl-Digest-MD5
  rpm -qa|grep perl-DBD-MySQL
  if [ $? -eq 1 ];then
    install_yum
    yum install -y perl-DBD-MySQL &>/dev/null  
    yum install -y perl-Digest-MD5 &>/dev/null  
    action "************安装perl-DBD-MySQL完成************" /bin/true  
    else
    	action "************已安装perl-DBD-MySQL包************" /bin/true 
  fi
  
  
  #安装Percona xtrabackup 2.4
  action "*************开始安装Percona xtrabackup 2.4**************" /bin/true
  rpm -ivh /opt/libev-4.15-3.el7.x86_64.rpm
  rpm -ivh /opt/percona-xtrabackup-24-2.4.20-1.el7.x86_64.rpm
  sleep 3
  #xtra=`xtrabackup --version`
  echo -e "\033[33m*******************************************完成Percona xtrabackup 2.4部署********************************************\033[0m"
cat > /tmp/xtrabackup2.4.log  << EOF
xtrabackup目录： /usr/bin/xtrabackup
xtrabackup版本： xtrabackup-2.4
EOF
  cat /tmp/xtrabackup2.4.log 
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/xtrabackup2.4.log 文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}


function install_xtrabackup8.0_el7() 
{
	echo ""
  echo -e "\033[33m**********************************************自动部署Percona xtrabackup 8.0*********************************************\033[0m" 
  
  #下载包
  if [ -f /opt/percona-xtrabackup-80-8.0.4-1.el7.x86_64.rpm ] && [ -f /opt/libev-4.15-3.el7.x86_64.rpm ] ;then
      echo "*****存在Percona xtrabackup 8.0安装包，无需下载*****"
  else
      ping -c 4 www.percona.com >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget http://rpmfind.net/linux/epel/7/x86_64/Packages/l/libev-4.15-3.el7.x86_64.rpm  -P /opt
      	#wget http://mirror.centos.org/centos/7/os/x86_64/Packages/perl-Digest-MD5-2.52-3.el7.x86_64.rpm -P /opt
      	wget https://www.percona.com/downloads/XtraBackup/Percona-XtraBackup-8.0.4/binary/redhat/7/x86_64/percona-xtrabackup-80-8.0.4-1.el7.x86_64.rpm  -P /opt
      else
        echo "please download Percona xtrabackup 8.0 package manual !"
		    exit $?
      fi 
  fi  
    
  #配yum安装perl-DBD-MySQL和perl-Digest-MD5
  rpm -qa|grep perl-DBD-MySQL
  if [ $? -eq 1 ];then
    install_yum
    yum install -y perl-DBD-MySQL &>/dev/null  
    yum install -y perl-Digest-MD5 &>/dev/null  
    action "************安装perl-DBD-MySQL完成************" /bin/true  
    else
    	action "************已安装perl-DBD-MySQL包************" /bin/true 
  fi
  
  
  #安装Percona xtrabackup 8.0
  action "*************开始安装Percona xtrabackup 8.0**************" /bin/true
  rpm -ivh /opt/libev-4.15-3.el7.x86_64.rpm
  rpm -ivh /opt/percona-xtrabackup-80-8.0.4-1.el7.x86_64.rpm
  sleep 3
  #xtra=`xtrabackup --version`
  echo -e "\033[33m*******************************************完成Percona xtrabackup 8.0部署********************************************\033[0m"
cat > /tmp/xtrabackup8.0.log  << EOF
xtrabackup目录： /usr/bin/xtrabackup
xtrabackup版本： xtrabackup-8.0
EOF
  cat /tmp/xtrabackup8.0.log 
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/xtrabackup8.0.log 文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}



# auto install postfix mail 
function install_mail() 
{
	echo ""
  echo -e "\033[33m****************************************************自动部署mail********************************************************\033[0m"
  
  #软件包：2:postfix-2.10.1-7.el7.x86_64 (base)需要：libmysqlclient.so.18(libmysqlclient_18)(64bit)
	if [ -f /opt/mysql-community-libs-compat-5.7.32-1.el7.x86_64.rpm ];then
		echo "*****存在libmysqlclient安装包，无需下载*****"
    else
      ping -c 4 cdn.mysql.com >/dev/null 2>&1
      if [ $? -eq 0 ];then
        wget https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-community-libs-compat-5.7.32-1.el7.x86_64.rpm -P /opt
      else
        echo "please download libmysqlclient package manual !"
		    exit $?
      fi 
  fi
  
  #配yum安装postfix
  rpm -qa|grep postfix
  #rpm -qa|grep postfix|xargs -i rpm -e --nodeps {} 
  if [ $? -eq 1 ];then
    install_yum
    yum install -y postfix*  &>/dev/null 
    action "*****安装postfix完成*****" /bin/true  
  fi 
  
  #配置
  #端口文件：/etc/postfix/master.cf ==》 smtp inet n - n - - smtpd
  sed -i 's/inet_interfaces = localhost/inet_interfaces = all/g'   /etc/postfix/main.cf  
cat >>  /etc/postfix/main.cf << EOF
mynetworks = 0.0.0.0/0
relayhost = ${RELAYHOST}
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
EOF
cat >>  /etc/postfix/sasl_passwd << EOF
${RELAYHOST} ${MAIL_USER}:${MAIL_PWD}
EOF
  #更新配置
  postmap /etc/postfix/sasl_passwd
  
  #启动postfix
  service postfix restart
  echo -e "\033[33m***************************************************完成邮件环境部署***************************************************\033[0m"
cat > /tmp/mail.log  << EOF
邮件版本：`postconf mail_version`
邮箱地址/端口：${RELAYHOST}
发件人邮箱：${MAIL_USER}
发件人密码：${MAIL_PWD}
EOF
  cat /tmp/mail.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/mail.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}


# auto install python2 on el6
# redhat6一般python是2.6，这里升级到python2.7
function install_python2_el6() 
{
	echo ""
  echo -e "\033[33m***************************************************python2.7安装****************************************************\033[0m" 
  
  #下载包
	if [ -f /opt/Python-2.7.11.tgz ] ;then
		echo "*****存在python安装包，无需下载*****"
    else
      ping -c 4 www.python.org >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz  -P /opt
      else
        echo "please download python2 package manual !"
		exit $?
      fi 
  fi

  #配yum安装openssl
  rpm -qa|grep openssl-devel
  #rpm -qa|grep postfix|xargs -i rpm -e --nodeps {} 
  if [ $? -eq 1 ];then
    install_yum
    yum install -y gcc gcc-c++ autoconf automake openssl openssl-devel &>/dev/null 
    action "*****安装python2依赖包完成*****" /bin/true  
    else
    	action "*****已安装python2依赖包*****" /bin/true 
  fi 

  #安装python2.7
  tar -xvzf  /opt/Python-2.7.11.tgz -C /opt/   &>/dev/null 
  cd Python-2.7.11  && ./configure --prefix=/usr/local/python2.7 && make && make install 
  
  #修改配置
  mv /usr/bin/python /usr/bin/python2.6
  ln -s /usr/local/python2.7/bin/python /usr/bin/python
  sed -i 's/\/usr\/bin\/python/\/usr\/bin\/python2.6/g' /usr/bin/yum
  sed -i 's/\/usr\/bin\/python/\/usr\/bin\/python2.6/g' /usr/libexec/urlgrabber-ext-down
  
  echo -e "\033[33m**************************************************完成python2.7安装***************************************************\033[0m"
cat > /tmp/python2.log  << EOF
python版本： `python -V`
python安装目录：/usr/bin/python
EOF
  cat /tmp/python2.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/python2.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}


# auto install python2/3 pip
#主要是离线安装，在线安装没啥必要，直接pip install即可
function install_pip() 
{
	echo ""
  echo -e "\033[33m***************************************************python升级安装pip****************************************************\033[0m" 
  
  #下载包
	if [ -f /opt/setuptools-38.5.2.zip ] && [ -f /opt/pip-18.0.tar.gz ];then
		echo "*****存在pip安装包，无需下载*****"
    else
      ping -c 4 files.pythonhosted.org >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget https://files.pythonhosted.org/packages/e0/02/2b14188e06ddf61e5b462e216b15d893e8472fca28b1b0c5d9272ad7e87c/setuptools-38.5.2.zip  -P /opt
        wget https://files.pythonhosted.org/packages/69/81/52b68d0a4de760a2f1979b0931ba7889202f302072cc7a0d614211bc7579/pip-18.0.tar.gz -P /opt
      else
        echo "please download pip package manual !"
		exit $?
      fi 
  fi

  #安装pip
  unzip /opt/setuptools-38.5.2.zip -d /opt/setuptools  &>/dev/null 
  cd /opt/setuptools ; python setup.py install
  tar -xvf /opt/pip-18.0.tar.gz -C /opt  &>/dev/null 
  cd /opt/pip-18.0 ; python setup.py build && python setup.py install
  ln -s /usr/local/bin/pip /usr/bin/pip 
  
  #pipversion=`pip -V`
  echo -e "\033[33m**************************************************完成pip升级安装***************************************************\033[0m"
cat > /tmp/pip.log  << EOF
python版本： `python -V`
python安装目录：/usr/bin/python
pip安装目录：/usr/bin/pip
pip版本： `pip -V`
EOF
  cat /tmp/pip.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/pip.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}


# auto install python3 and pip3
#主要是离线安装，在线安装没啥必要，直接pip install即可
function install_python3_el7() 
{
	echo ""
    echo -e "\033[33m****************************************************python3安装*****************************************************\033[0m" 
  
  #下载包
	if [ -f /opt/Python-3.7.0.tar.xz ];then
		echo "*****存在python3安装包，无需下载*****"
    else
      ping -c 4 cdn.mysql.com >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget https://www.python.org/ftp/python/3.7.0/Python-3.7.0.tar.xz -O /opt/Python-3.7.0.tar.xz 
      else
        echo "please download python3 package manual !"
		exit $?
      fi 
  fi

  #配yum安装openssl
  rpm -qa|grep libffi-devel
  #rpm -qa|grep postfix|xargs -i rpm -e --nodeps {} 
  if [ $? -eq 1 ];then
    install_yum
    yum install  openldap-devel libffi-devel *zlib* bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel gcc gcc-c++ autoconf automake openssl openssl-devel -y &>/dev/null 
    action "*****安装python3依赖包完成*****" /bin/true  
    else
    	action "*****已安装python3依赖包*****" /bin/true 
  fi 

  #安装python3 
  tar -xvf /opt/Python-3.7.0.tar.xz -C /opt && mkdir -p /usr/local/python/lib  &>/dev/null 
  cd /opt/Python-3.7.0 ; ./configure --enable-shared --with-ssl --prefix=/usr/local/python/ LDFLAGS="-Wl,-rpath /usr/local/python/lib"
  make && make install 
  #链接
  
  #修改配置
  mv /usr/bin/python /usr/bin/python2.7
  ln -fs /usr/local/python/bin/python3.7 /usr/bin/python
  ln -fs /usr/local/python/bin/pip3 /usr/bin/pip
  sed -i 's/\/usr\/bin\/python/\/usr\/bin\/python2.7/g' /usr/bin/yum
  sed -i 's/\/usr\/bin\/python/\/usr\/bin\/python2.7/g' /usr/libexec/urlgrabber-ext-down

  echo -e "\033[33m**************************************************完成python3安装***************************************************\033[0m"
cat > /tmp/python3.log  << EOF
python版本： `python -V`
python安装目录：/usr/bin/python
EOF
  cat /tmp/python3.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/python3.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}

# auto install requests module on python3
#主要是离线安装，在线安装没啥必要，直接pip install即可
function install_requests_py3() 
{
	echo ""
    echo -e "\033[33m***********************************************基于python3安装requests模块************************************************\033[0m" 
  
  #下载包
	if [ -f /opt/requests-2.22.0.tar.gz ] && [ -f /opt/idna-2.8.tar.gz ] && [ -f /opt/chardet-3.0.4.tar.gz ] && [ -f /opt/certifi-2019.9.11.tar.gz ] && [ -f /opt/urllib3-1.25.6.tar.gz ];then
		echo "*****存在requests安装包，无需下载*****"
    else
      ping -c 4 files.pythonhosted.org >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget https://files.pythonhosted.org/packages/01/62/ddcf76d1d19885e8579acb1b1df26a852b03472c0e46d2b959a714c90608/requests-2.22.0.tar.gz -O /opt/requests-2.22.0.tar.gz
      	wget https://files.pythonhosted.org/packages/fc/bb/a5768c230f9ddb03acc9ef3f0d4a3cf93462473795d18e9535498c8f929d/chardet-3.0.4.tar.gz -O /opt/chardet-3.0.4.tar.gz
      	wget https://files.pythonhosted.org/packages/62/85/7585750fd65599e88df0fed59c74f5075d4ea2fe611deceb95dd1c2fb25b/certifi-2019.9.11.tar.gz -O /opt/certifi-2019.9.11.tar.gz
      	wget https://files.pythonhosted.org/packages/ff/44/29655168da441dff66de03952880c6e2d17b252836ff1aa4421fba556424/urllib3-1.25.6.tar.gz -O /opt/urllib3-1.25.6.tar.gz
      	wget https://files.pythonhosted.org/packages/ad/13/eb56951b6f7950cadb579ca166e448ba77f9d24efc03edd7e55fa57d04b7/idna-2.8.tar.gz -O /opt/idna-2.8.tar.gz 
      else
        echo "please download requests package manual !"
		exit $?
      fi 
  fi
  #安装顺序：certifi、chardet、idna、urllib3、requests
  #安装certifi
  tar -xvf /opt/certifi-2019.9.11.tar.gz  -C /opt  &>/dev/null 
  cd /opt/certifi-2019.9.11 ; python setup.py install &>/dev/null
  action "*****certifi-2019.9.11依赖包安装成功*****" /bin/true 
  #安装chardet
  tar -xvf /opt/chardet-3.0.4.tar.gz  -C /opt  &>/dev/null 
  cd /opt/chardet-3.0.4; python setup.py install &>/dev/null
  action "*****chardet-3.0.4依赖包安装成功*****" /bin/true 
  #安装idna
  tar -xvf /opt/idna-2.8.tar.gz  -C /opt  &>/dev/null 
  cd /opt/idna-2.8; python setup.py install &>/dev/null
  action "*****idna-2.8依赖包安装成功*****" /bin/true 
  #安装urllib3
  tar -xvf /opt/urllib3-1.25.6.tar.gz  -C /opt  &>/dev/null 
  cd /opt/urllib3-1.25.6; python setup.py install &>/dev/null
  action "*****urllib3-1.25.6依赖包安装成功*****" /bin/true 
  #安装requests
  tar -xvf /opt/requests-2.22.0.tar.gz  -C /opt  &>/dev/null 
  cd /opt/requests-2.22.0; python setup.py install &>/dev/null
  action "*****requests-2.22.0依赖包安装成功*****" /bin/true 

  echo -e "\033[33m************************************************基于python3完成安装requests模块*************************************************\033[0m"
cat > /tmp/requests.log  << EOF
python版本： `python -V`
requests版本： requests-2.22.0
EOF
  cat /tmp/requests.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/requests.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}

# auto install ES7.6 on el7
# ES7建议安装ik-analyzer插件并设置为默认分词器。其采用了多子处理器分析模式，支持：英文字母、数字、中文词汇等分词处理，
# 兼容韩文、日文字符，满足决大部份的中英文混用场景。
function install_es7_el7() 
{
	echo ""
  echo -e "\033[33m****************************************************安装ElasticSearch 7.7.0*****************************************************\033[0m" 
  #action "********初始化JAVA环境********" /bin/true
  #install_jdk

  #下载包
	if [ -f /opt/elasticsearch-7.7.0-x86_64.rpm ] && [ -f /opt/elasticsearch-analysis-ik-7.7.0.zip ] ;then
		echo "*****存在ElasticSearch 7.7.0安装包，无需下载*****"
    else
      ping -c 4 artifacts.elastic.co >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.7.0-x86_64.rpm -O /opt/elasticsearch-7.7.0-x86_64.rpm
      	wget https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.7.0/elasticsearch-analysis-ik-7.7.0.zip  -O /opt/elasticsearch-analysis-ik-7.7.0.zip 	
      else
        echo "please download ES7 package manual !"
		exit $?
      fi 
  fi

  #安装es7.6 
  action "********安装ElasticSearch 7.7.0服务********" /bin/true
  chmod u+x /opt/elasticsearch-7.7.0-x86_64.rpm && rpm -ivh /opt/elasticsearch-7.7.0-x86_64.rpm
  
  #建目录及授权
  mkdir -p $ES_HOME/data &&  mkdir -p $ES_HOME/log
  chown -R elasticsearch:elasticsearch $ES_HOME && chmod -R 755 $ES_HOME
  
  #修改ES配置文件
  cp /etc/elasticsearch/elasticsearch.yml /etc/elasticsearch/elasticsearch.yml_bak &>/dev/null 
cat > /etc/elasticsearch/elasticsearch.yml << EOF 
cluster.name: es-cluster
# 设定本机节点名 
node.name: es_node
# 设定集群主节点清单
cluster.initial_master_nodes: ["es_node"] 
path.data: ${ES_HOME}/data
path.logs: ${ES_HOME}/log
bootstrap.memory_lock: false
bootstrap.system_call_filter: false
# 允许从其它机器访问
network.host: 0.0.0.0
http.port: ${ES_PORT}
discovery.zen.ping.unicast.hosts: ["${ES_IP}:${ES_PORT}"]
EOF
   
  #安装分词器：ik-analyzer插件
  #默认情况下，ES使用内置的标准分词器，对文本进行解析。但是对于中文，其会拆解为一个一个的汉字，最终失去了分词的意义，所以安装分词器：ik-analyzer插件
  action "********安装ik-analyzer插件********" /bin/true
  mkdir -p /usr/share/elasticsearch/plugins/ik
  unzip /opt/elasticsearch-analysis-ik-7.7.0.zip -d /usr/share/elasticsearch/plugins/ik/ &>/dev/null 
  chown -R elasticsearch:elasticsearch /usr/share/elasticsearch/plugins/ &&  chmod -R 755  /usr/share/elasticsearch/plugins/
  sleep 2
#在filebeat配置文件中为索引模板添加默认分词器属性。未来新创建的索引均引用此属性:
#setup.template.settings:
#  index.analysis.analyzer.default.type: "ik_max_word"
#  index.analysis.analyzer.default_search.type: "ik_max_word"
#setup.template.overwrite: true
#在Linux终端中执行如下命令，为现有所有索引，设置默认分词器属性:
#curl -X POST "172.16.20.143:9200/_all/_close"
#curl -X PUT  -H'Content-Type: application/json' 'http://172.16.20.143:9200/_all/_settings?preserve_existing=true' -d '{
#  "index.analysis.analyzer.default.type" : "ik_max_word",
#  "index.analysis.analyzer.default_search.type" : "ik_max_word"
#}'
#curl -X POST "172.16.20.143:9200/_all/_open"


  #启动ES并初始化数据
  action "********启动es并初始化数据********" /bin/true
  systemctl daemon-reload && systemctl enable elasticsearch.service 
  systemctl restart elasticsearch.service
  es_version=`curl -XGET ${ES_IP}:${ES_PORT}`
  echo -e "\033[33m**************************************************完成ElasticSearch 7.7.0安装***************************************************\033[0m"
cat > /tmp/es7.log  << EOF
ES服务器IP： ${ES_IP}
ES服务器端口:${ES_PORT}
ES数据目录： ${ES_HOME}/data
ES日志目录： ${ES_HOME}/log
ES详细信息： ${es_version}
EOF
  cat /tmp/es7.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/es7.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}



# auto install Kibana7.6 on el7
function install_kibana7_el7() 
{
	echo ""
  echo -e "\033[33m****************************************************安装Kibana 7.7.0*****************************************************\033[0m" 

  #下载包
	if [ -f /opt/kibana-7.7.0-x86_64.rpm ] ;then
		echo "*****存在Kibana 7.7.0安装包，无需下载*****"
    else
      ping -c 4 artifacts.elastic.co >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget https://artifacts.elastic.co/downloads/kibana/kibana-7.7.0-x86_64.rpm -O /opt/kibana-7.7.0-x86_64.rpm
      else
        echo "please download kibana7.6 package manual !"
		exit $?
      fi 
  fi

  #安装kibana7.6 
  action "********安装Kibana 7.7.0服务********" /bin/true
  chmod u+x /opt/kibana-7.7.0-x86_64.rpm && rpm -ivh /opt/kibana-7.7.0-x86_64.rpm
  
  #修改kibana配置文件
  cp /etc/kibana/kibana.yml /etc/kibana/kibana.yml_bak 
cat > /etc/kibana/kibana.yml << EOF 
server.port: ${KIBANA_PORT}
server.host: "${KIBANA_IP}"
#通过反向代理访问
server.basePath: "/kibana"
kibana.index: ".kibana"
elasticsearch.hosts: ["http://${ES_IP}:${ES_PORT}"]
# 7.x后官方自带汉化
i18n.locale: "zh-CN"
EOF
  

  #启动kibana并初始化数据
  action "********启动kibana并初始化数据********" /bin/true
  systemctl daemon-reload && systemctl enable kibana.service 
  systemctl restart kibana.service
  
  echo -e "\033[33m**************************************************完成Kibana 7.7.0安装***************************************************\033[0m"
cat > /tmp/kibana7.log  << EOF
KIBANA服务器IP： ${KIBANA_IP}
KIBANA服务器端口:${KIBANA_PORT}
KIBANA服务版本： Kibana 7.7.0
KIBANA访问地址： http://${KIBANA_IP}:${KIBANA_PORT}/kibana
EOF
  cat /tmp/kibana7.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/kibana7.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}


# auto install Filebeat7.6 on el7
function install_filebeat7_el7() 
{
	echo ""
  echo -e "\033[33m****************************************************安装Filebeat 7.7.0*****************************************************\033[0m" 

  #下载包
	if [ -f /opt/filebeat-7.7.0-x86_64.rpm ] ;then
		echo "*****存在Filebeat 7.7.0安装包，无需下载*****"
    else
      ping -c 4 artifacts.elastic.co >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-7.7.0-x86_64.rpm -O /opt/filebeat-7.7.0-x86_64.rpm
      else
        echo "please download Filebeat7.6 package manual !"
		exit $?
      fi 
  fi

  #安装filebeat7.6 
  action "********安装filebeat 7.7.0服务********" /bin/true
  chmod u+x /opt/filebeat-7.7.0-x86_64.rpm && rpm -ivh /opt/filebeat-7.7.0-x86_64.rpm
  
  #修改kibana配置文件
  cp /etc/filebeat/filebeat.yml /etc/filebeat/filebeat.yml_bak 
cat > /etc/filebeat/filebeat.yml << EOF 
filebeat.inputs:
- type: log
  enabled: true
  paths:
    - /lcp_logs/*.log
  encoding: utf8
  multiline.pattern: '^[[:space:]]+(at|\.{3})[[:space:]]+\b|^Caused by:'
  multiline.negate: false
  multiline.match: after
  multiline.max_lines: 1000
filebeat.config.modules:
  path: /etc/filebeat/modules.d/*.yml
  reload.enabled: false
setup.template.settings:
  #number_of_shards  是数据分片数，默认为5
  index.number_of_shards: 1
  #副本计数，默认为1
  index.number_of_replicas: 0
  index.analysis.analyzer.default.type: "ik_max_word"
  index.analysis.analyzer.default_search.type: "ik_max_word"
setup.template.overwrite: true
setup.kibana:
  host: "${KIBANA_IP}:${KIBANA_PORT}"
output.elasticsearch:
  hosts: ["${ES_IP}:${ES_PORT}"]
setup.ilm.rollover_alias: "fsl_prod.ams"
setup.ilm.pattern: "{now/d{yyyy.MM.dd|+08:00}}-000001"
processors:
  - add_host_metadata: ~
  - add_cloud_metadata: ~
EOF

  #启动filebeat并初始化数据
  action "********启动filebeat并初始化数据********" /bin/true
  systemctl daemon-reload && systemctl enable filebeat.service 
  systemctl restart filebeat.service
  #nohup ./filebeat -e -c filebeat.yml >/dev/null 2>&1 &
  
  echo -e "\033[33m**************************************************完成Filebeat 7.7.0安装***************************************************\033[0m"
cat > /tmp/filebeat7.log << EOF
filebeat版本：   7.7.0
filebeat路径:    /usr/bin/filebeat
filebeat配置kibana： ${KIBANA_IP}:${KIBANA_PORT}
filebeat配置elasticsearch： ${ES_IP}:${ES_PORT}
EOF
  cat /tmp/filebeat7.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/filebeat7.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}



# auto install rsync on el7
function install_rsync3_el7() 
{
  echo ""
  echo -e "\033[33m****************************************************安装Rsync 3.1.2*****************************************************\033[0m" 

  #下载包
  if [ -f /opt/rsync*.tar.gz ] ;then
	  echo "*****存在rsync安装包，无需下载*****"
  else
      ping -c 4 download.samba.org >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget https://download.samba.org/pub/rsync/src/rsync-3.1.2.tar.gz -O /opt/rsync-3.1.2.tar.gz
      else
        echo "please download Rsync-3.1.2 package manual !"
		exit $?
      fi 
  fi

  #安装rsync 3.1.2
  action "********编译安装rsync 远程同步服务********" /bin/true
  chmod u+x /opt/rsync-3.1.2.tar.gz ;tar -xvf /opt/rsync-3.1.2.tar.gz -C /opt  &>/dev/null
  cd /opt/rsync-3.1.2 && ./configure --prefix=${RSYNC_HOME}  && make &&  make install
  mkdir -p /opt/rsync
  
  #修改rsync配置文件
  cp ${RSYNC_HOME}/rsyncd.conf ${RSYNC_HOME}/rsyncd.conf_bak  &>/dev/null  
cat > ${RSYNC_HOME}/rsyncd.conf << EOF 
#全局参数
uid = root
gid = root
use chroot = no
max connections = 5
strict modes = yes
port = 8888
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsyncd.log

#模块
[jpom]
path = /opt/rsync
comment = jpom deploy
ignore errors
read only = false
list = no
auth users = rsync
secrets file = ${RSYNC_HOME}/rsyncd.secrets
EOF

cat > ${RSYNC_HOME}/rsyncd.secrets << EOF
${RSYNC_USER}:${RSYNC_PWD}
EOF
  #授权
  chmod -R 755 ${RSYNC_HOME} && chmod 600 ${RSYNC_HOME}/rsyncd.secrets
  #启动rsync
  action "********启动rsync********" /bin/true
  ${RSYNC_HOME}/bin/rsync --daemon --config=${RSYNC_HOME}/rsyncd.conf
  echo -e "\033[33m**************************************************完成Rsync 3.1.2安装***************************************************\033[0m"
cat > /tmp/rsync.log << EOF
rsync版本：   3.1.2
rsync目录：   ${RSYNC_HOME}
rsync用户名： ${RSYNC_USER}
rsync密码：   ${RSYNC_PWD}
rsync密码：   ${RSYNC_PORT}
EOF
  cat /tmp/rsync.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/rsync.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}



# auto install zabbix agent on el7
function install_zabbixagent_el7() 
{
  echo ""
  echo -e "\033[33m****************************************************安装Zabbix agent 4.2.6*****************************************************\033[0m" 

  #下载包
  if [ -f /opt/zabbix-agent-4.2.6-1.el7.x86_64.rpm ] ;then
	  echo "*****存在zabbix agent安装包，无需下载*****"
  else
      ping -c 4 repo.zabbix.com >/dev/null 2>&1
      if [ $? -eq 0 ];then
      	wget https://repo.zabbix.com/zabbix/4.2/rhel/7/x86_64/zabbix-agent-4.2.6-1.el7.x86_64.rpm -O /opt/zabbix-agent-4.2.6-1.el7.x86_64.rpm
      else
        echo "please download zabbix-agent-4.2.6 package manual !"
		exit $?
      fi 
  fi

  #安装Zabbix agent
  action "********安装Zabbix agent 4.2.6********" /bin/true
  chmod u+x /opt/zabbix-agent-4.2.6-1.el7.x86_64.rpm && chmod u+x /opt/zabbix_scripts.zip
  rpm -ivh /opt/zabbix-agent-4.2.6-1.el7.x86_64.rpm
  action "********覆盖Zabbix agent脚本********" /bin/true
  unzip /opt/zabbix_scripts.zip -d /etc/zabbix/zabbix_agentd.d/
  mv /etc/zabbix/zabbix_agentd.d/userparameter_mysql.conf /etc/zabbix/zabbix_agentd.d/userparameter_mysql.bak
  
  #修改zabbix agent配置文件
cat > /etc/zabbix/zabbix_agentd.conf << EOF
PidFile=/var/run/zabbix/zabbix_agentd.pid
LogFile=/var/log/zabbix/zabbix_agentd.log
LogFileSize=0
Server=${ZABBIX_SERVER}
ServerActive=${ZABBIX_SERVER}
ListenPort=${ZABBIX_PORT}
Hostname=${AGENT_HOSTNAME}
AllowRoot=1
Include=/etc/zabbix/zabbix_agentd.d/*.conf
UnsafeUserParameters=1
EOF

  #授权
  chown -R zabbix:zabbix /etc/zabbix/ && chmod -R 755   /etc/zabbix/
  action "********启动Zabbix agent********" /bin/true
  systemctl enable zabbix-agent
  systemctl start  zabbix-agent
  systemctl status zabbix-agent
  echo -e "\033[33m**************************************************完成zabbix-agent安装***************************************************\033[0m"
cat > /tmp/zabbix-agent.log << EOF
zabbix-agent版本：   4.2.6
zabbix-server：      ${ZABBIX_SERVER}
zabbix-server端口：  ${ZABBIX_PORT}
zabbix-agent IP：    ${IPADDR}
zabbix-agent主机名： ${AGENT_HOSTNAME}
EOF
  cat /tmp/zabbix-agent.log
  echo -e "\e[1;31m 以上信息10秒后消失，保存在/tmp/zabbix-agent.log文件下 \e[0m"
  echo -e "\033[33m************************************************************************************************************************\033[0m"
  echo ""
  sleep 10
}



#menu2
menu2(){
while true;
do
 clear
cat <<EOF
----------------------------------------
|****Please Enter Your Choice:[0-11]****|
----------------------------------------
(1)  新建一个用户并将其加入visudo
(2)  配置YUM源镜像
(3)  配置中文字符集
(4)  禁用SELINUX及关闭防火墙
(5)  设置时间同步
(6)  自动部署jdk
(7)  自动部署tomcat
(8)  自动部署redis
(9)  自动部署mysql5.7
(10) 自动部署mysql8.0
(11) 自动部署邮件
(12) 自动部署python2
(13) 自动部署pip(升级)
(14) 自动部署python3及pip
(15) 自动部署ElasticSearch7.7.0
(16) 自动部署Kibana7.7.0
(17) 自动部署Filebeat7.7.0
(18) 自动部署Percona Server for MySQL 8.0
(19) 自动部署mariadb-10.4.13
(20) 自动部署xtrabackup-2.4
(21) 自动部署xtrabackup-8.0
(22) 自动部署requests(python3)
(23) 自动部署Rsync-3.1.2
(24) 自动部署zabbix-agent-4.2.6
(0)  返回上一级菜单

EOF
 read -p "Please enter your Choice[0-24]: " input2
 case "$input2" in
   0)
   clear
   break 
   ;;
   1)
   addUser
   ;;
   2)
   install_yum
   ;;
   3)
   initI18n
   ;;
   4)
   initFirewall
   ;;
   5)
   syncSysTime
   ;;
   6)
   install_jdk
   ;;
   7)
   install_tomcat
   ;;
   8)
   install_redis
   ;;
   9)
   install_mysql5.7_el7
   ;;
   10)
   install_mysql8_el7
   ;;
   11)
   install_mail
   ;;
   12)
   install_python2_el6
   ;;
   13)
   install_pip
   ;;
   14)
   install_python3_el7
   ;;
   15)
   install_es7_el7
   ;;
   16)
   install_kibana7_el7
   ;;
   17)
   install_filebeat7_el7
   ;;
   18)
   install_percona_server8_el7
   ;;
   19)
   install_mariadb10_el7
   ;;
   20)
   install_xtrabackup2.4_el7
   ;;
   21)
   install_xtrabackup8.0_el7
   ;;
   22)
   install_requests_py3
   ;;
   23)
   install_rsync3_el7
   ;;
   24)
   install_zabbixagent_el7
   ;;
   *) echo "----------------------------------"
      echo "|          Warning!!!            |"
      echo "|   Please Enter Right Choice!   |"
      echo "----------------------------------"
      for i in `seq -w 3 -1 1`
        do 
          echo -ne "\b\b$i";
          sleep 1;
        done
      clear
 esac
done
}
#initTools
#menu
while true;
do
 clear
 echo "========================================"
 echo '          Linux Optimization            '   
 echo "========================================"
cat << EOF
|-----------System Infomation-----------
| DATE       :$DATE
| HOSTNAME   :$HOSTNAME
| USER       :$USER
| IP         :$IPADDR
| GATEWAY    :$GATEWAY
| DNS        :$DNS
| DISK_USED  :$DISK_SDA
| CPU_AVERAGE:$cpu_uptime
----------------------------------------
|****Please Enter Your Choice:[1-3]****|
----------------------------------------
(1) 一键部署yum\jdk\tomcat\redis\mysql\mail
(2) 自定义部署(推荐)
(3) 退出
EOF
 #choice
 read -p "Please enter your choice[0-3]: " input1
 case "$input1" in
 1) 
   install_Yum
   initI18n
   initFirewall
   syncSysTime
   install_jdk
   install_tomcat
   install_redis
   install_mysql5.7_el7
   install_mail
   ;;
 2)
   menu2
   ;;
 3) 
   clear 
   break
   ;;
 *)   
   echo "----------------------------------"
   echo "|          Warning!!!            |"
   echo "|   Please Enter Right Choice!   |"
   echo "----------------------------------"
   for i in `seq -w 3 -1 1`
       do
         echo -ne "\b\b$i";
         sleep 1;
       done
   clear
 esac  
done
